{% extends "base.html" %}

{% block title %}登录 - MinerU 文档解析系统{% endblock %}

{% block page_title %}用户登录{% endblock %}

{% block login_content %}
<div class="min-h-screen flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
        <div>
            <div class="mx-auto h-12 w-12 flex items-center justify-center rounded-full bg-blue-500">
                <i class="fas fa-file-alt text-white text-xl"></i>
            </div>
            <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">
                MinerU 文档解析系统
            </h2>
            <p class="mt-2 text-center text-sm text-gray-600">
                请登录您的账户
            </p>
        </div>
        
        <form class="mt-8 space-y-6" id="loginForm">
            <div class="rounded-md shadow-sm -space-y-px">
                <div>
                    <label for="username" class="sr-only">用户名</label>
                    <input id="username" name="username" type="text" required 
                           class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-t-md focus:outline-none focus:ring-blue-500 focus:border-blue-500 focus:z-10 sm:text-sm" 
                           placeholder="用户名">
                </div>
                <div>
                    <label for="password" class="sr-only">密码</label>
                    <input id="password" name="password" type="password" required 
                           class="appearance-none rounded-none relative block w-full px-3 py-2 border border-gray-300 placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-none focus:ring-blue-500 focus:border-blue-500 focus:z-10 sm:text-sm" 
                           placeholder="密码">
                </div>
            </div>

            <div class="flex items-center justify-between">
                <div class="flex items-center">
                    <input id="remember-me" name="remember-me" type="checkbox" 
                           class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                    <label for="remember-me" class="ml-2 block text-sm text-gray-900">
                        记住我
                    </label>
                </div>

                <div class="text-sm">
                    <a href="#" class="font-medium text-blue-600 hover:text-blue-500">
                        忘记密码？
                    </a>
                </div>
            </div>

            <div>
                <button type="submit" 
                        class="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                    <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                        <i class="fas fa-sign-in-alt text-blue-500 group-hover:text-blue-400"></i>
                    </span>
                    登录
                </button>
            </div>
        </form>
        
        <!-- 错误消息显示 -->
        <div id="errorMessage" class="hidden bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative">
            <span class="block sm:inline" id="errorText"></span>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// SHA-256 哈希函数
async function sha256(message) {
    const msgBuffer = new TextEncoder().encode(message);
    const hashBuffer = await crypto.subtle.digest('SHA-256', msgBuffer);
    const hashArray = Array.from(new Uint8Array(hashBuffer));
    const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    return hashHex;
}

// 密码强度验证
function validatePasswordStrength(password) {
    const minLength = 6;
    const hasUpperCase = /[A-Z]/.test(password);
    const hasLowerCase = /[a-z]/.test(password);
    const hasNumbers = /\d/.test(password);
    const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
    
    let strength = 0;
    let messages = [];
    
    if (password.length >= minLength) {
        strength += 25;
    } else {
        messages.push('密码长度至少8位');
    }
    
    if (hasUpperCase) strength += 25;
    else messages.push('需要包含大写字母');
    
    if (hasLowerCase) strength += 25;
    else messages.push('需要包含小写字母');
    
    if (hasNumbers) strength += 25;
    else messages.push('需要包含数字');
    
    if (hasSpecialChar) strength += 25;
    else messages.push('需要包含特殊字符');
    
    return {
        strength: Math.min(strength, 100),
        valid: password.length >= minLength && hasUpperCase && hasLowerCase && hasNumbers,
        messages: messages
    };
}

document.getElementById('loginForm').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;
    const errorDiv = document.getElementById('errorMessage');
    const errorText = document.getElementById('errorText');
    
    // 隐藏错误消息
    errorDiv.classList.add('hidden');
    
    // 密码强度验证
    const passwordValidation = validatePasswordStrength(password);
    if (!passwordValidation.valid) {
        errorText.textContent = '密码强度不足: ' + passwordValidation.messages.join(', ');
        errorDiv.classList.remove('hidden');
        return;
    }
    
    try {
        // 对密码进行SHA-256哈希
        const hashedPassword = await sha256(password);
        
        const response = await fetch('/api/v1/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: username,
                password: hashedPassword,
                client_hash: true  // 标识客户端已哈希
            })
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 登录成功，保存token并跳转到仪表板
            const token = data.access_token;
            localStorage.setItem('auth_token', token);
            window.location.href = `/web/dashboard?token=${token}`;
        } else {
            // 显示错误消息
            errorText.textContent = data.detail || '登录失败';
            errorDiv.classList.remove('hidden');
        }
    } catch (error) {
        console.error('登录请求失败:', error);
        errorText.textContent = '网络错误，请稍后重试';
        errorDiv.classList.remove('hidden');
    }
});

// 实时密码强度检查
document.getElementById('password').addEventListener('input', function(e) {
    const password = e.target.value;
    const validation = validatePasswordStrength(password);
    
    // 移除现有的强度指示器
    const existingIndicator = document.getElementById('password-strength');
    if (existingIndicator) {
        existingIndicator.remove();
    }
    
    if (password.length > 0) {
        const indicator = document.createElement('div');
        indicator.id = 'password-strength';
        indicator.className = 'mt-2 text-sm';
        
        let strengthClass = '';
        let strengthText = '';
        
        if (validation.strength >= 75) {
            strengthClass = 'text-green-600';
            strengthText = '强';
        } else if (validation.strength >= 50) {
            strengthClass = 'text-yellow-600';
            strengthText = '中等';
        } else {
            strengthClass = 'text-red-600';
            strengthText = '弱';
        }
        
        indicator.innerHTML = `
            <span class="${strengthClass}">密码强度: ${strengthText}</span>
            <div class="w-full bg-gray-200 rounded-full h-2 mt-1">
                <div class="h-2 rounded-full ${strengthClass.replace('text-', 'bg-')}" style="width: ${validation.strength}%"></div>
            </div>
        `;
        
        e.target.parentNode.appendChild(indicator);
    }
});
</script>
{% endblock %}